const router = require('koa-router')()
const Sysuser = require('../class/user')
const { Fb } = require('../class/utils')

router.prefix('/')

// 添加用户
router.post('/createUser.do', async ctx => {
    const form = ctx.request.body
    form.name = form.uname;
    let userData = await Fb.callback(Sysuser.select(form, 1, 9999999));
    if (userData.data.count > 0) {
        ctx.body = Fb.error('用户名或姓名被占用！');
        return
    }
    ctx.body = await Fb.callback(Sysuser.create(form))
})

// 获取用户列表
router.post('/getUserList.do', async ctx => {
    const form = ctx.request.body
    let nowPage = parseInt(form.nowPage) || 1
    let pageSize = parseInt(form.pageSize) || 9999999
    ctx.body = await Fb.callback(Sysuser.select(form, nowPage, pageSize))
})

// 查看用户信息
router.post('/getUserDetail.do', async ctx => {
    const form = ctx.request.body
    ctx.body = await Fb.callback(Sysuser.details(form.id))
})

// 登陆
router.post('/login.do', async ctx => {
    const form = ctx.request.body
    const sqlPass = await (Sysuser.getPassword(form.uname))
    if(sqlPass == null){
        ctx.body = Fb.error('该账号不存在');
        return false
    }
    if(sqlPass.status == '已注销' || sqlPass.delstatus == '是'){
        ctx.body = Fb.error('该账号已停用！');
        return false
    }
    if (sqlPass.upass == form.upass) {
        ctx.body = Fb.success(sqlPass)
    }else{
        ctx.body = Fb.error('密码错误');
    }
})

// 更新用户信息
router.post('/updateUser.do', async ctx => {
    const form = ctx.request.body
    ctx.body = await Fb.callback(Sysuser.update(form))
})

// 注销用户
router.post('/upUserStatus.do', async ctx => {
    const form = ctx.request.body
    ctx.body = await Fb.callback(Sysuser.updateStatus(form))
})

// 更新删除用户
router.post('/deleteUser.do', async ctx => {
    const form = ctx.request.body
    ctx.body = await Fb.callback(Sysuser.delete(form))
})

//重定向
router.get('/like', async ctx => {
    ctx.response.redirect('/like.html');
})

router.get('/mmp', async ctx => {
    ctx.response.redirect('/mmp/pages/login.html');
})

//微信公众号服务器验证
router.get('/wx', async ctx => {
    let TOKEN='sky123456';
    console.log(ctx.request.query);
    let params = ctx.request.query

    let checkSignature = (params,token) => {
        var key=[token,params.timestamp,params.nonce].sort().join(''); 
         //将token （自己设置的） 、timestamp（时间戳）、nonce（随机数）三个参数进行字典排序
        var sha1=require('crypto').createHash('sha1');
         //将上面三个字符串拼接成一个字符串再进行sha1加密
        sha1.update(key);
        return sha1.digest('hex') ==params.signature;
         //将加密后的字符串与signature进行对比，若成功，返回echostr
    }

    if(!checkSignature(params,TOKEN)){
        //如果签名不对，结束请求并返回
        ctx.body = 'signature fail';
    }

    if (ctx.req.method == "GET") {
        //如果请求是GET，返回echostr用于通过服务器有效校验
        ctx.body = params.echostr;

    }else{
        //否则是微信给开发者服务器的POST请求
         var postdata='';
        ctx.req.addListener("data",function(postchunk){
            postdata+=postchunk;
        });
        //获取到了POST数据
        ctx.req.addListener("end",function(){
            console.log(postdata);
            ctx.body = 'success ';
        });
    }

    // ctx.response.redirect('/like.html');
})

module.exports = router